<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="30">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model.trim="queryData.query"
            clearable
            keyup.enter="onSearch"
            @clear="onClear"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="onSearch"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <template>
        <el-table :data="userList" style="width: 100%" border stripe>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"> </el-table-column>
          <el-table-column prop="role_name" label="角色"> </el-table-column>
          <el-table-column prop="mg_state" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChanged(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEdit(scope.row)"
              ></el-button>
              <!-- 删除按钮 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="doDel(scope.row.id)"
              ></el-button>
              <!-- 分配角色按钮 -->
              <el-tooltip
                effect="dark"
                content="分配角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="showRoleDialog(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @closed="addDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doEdit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="isRoleShow"
      width="50%"
      @close="setRoleDialogClose"
    >
      <p>当前的用户: {{ curUser.username }}</p>
      <p>当前的角色: {{ curUser.role_name }}</p>
      <p>
        分配新角色:
        <el-select v-model="selRoleId" placeholder="请选择">
          <el-option
            v-for="item in selRoleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isRoleShow = false">取 消</el-button>
        <el-button type="primary" @click="doSetRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: 'users',
  data() {
    return {
      isRoleShow: false,
      curUser: {},
      selRoleId: '',
      selRoleList: [],
      // userInfo:{},
      queryData: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2,
      },
      userList: [],
      total: 0,
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名~亲', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在3到15个字符~亲',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码哦~亲', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在3到15个字符~亲',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱哦~亲', trigger: 'blur' },
          {
            type: 'email',
            message: '邮箱格式好像不争取哦~亲',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            pattern: /^(13|14|15|16|17|18|19)[0-9]\d{8}$/,
            message: '请输入正确的手机号哦~亲',
            trigger: 'blur',
          },
        ],
      },
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {
        id: -1,
        username: '',
        email: '',
        mobile: '',
      },

      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱哦~亲', trigger: 'blur' },
          {
            type: 'email',
            message: '邮箱格式好像不争取哦~亲',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            pattern: /^(13|14|15|16|17|18|19)[0-9]\d{8}$/,
            message: '请输入正确的手机号哦~亲',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$axios({
        method: 'get',
        url: 'users',
        params: this.queryData,
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryData.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryData.pagenum = newPage
      this.getUserList()
    },
    async userStateChanged(userInfo) {
      const { data: res } = await this.$axios({
        url: `users/${userInfo.id}/state/${userInfo.mg_state}`,
        method: 'put',
      })
      if (res.meta.status != 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$msg.error(res.meta.msg)
      }
      this.$msg.success(res.meta.msg)
    },
    onSearch() {
      if (this.queryData.query.length === 0) {
        return this.$msg.error('请输入查询关键字哦!')
      }
      this.getUserList()
    },
    onClear() {
      this.getUserList()
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { data: res } = await this.$axios.post('users', this.addForm)

        if (res.meta.status !== 201) {
          this.$msg.error('添加用户失败！')
        }

        this.$msg.success('添加用户成功！')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUserList()
      })
    },
    showEdit(userData) {
      this.editForm.id = userData.id
      this.editForm.username = userData.username
      this.editForm.email = userData.email
      this.editForm.mobile = userData.mobile
      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    doEdit() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户信息的数据请求
        const { data: res } = await this.$axios.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        )
        if (res.meta.status !== 200) {
          return this.$msg.error('更新用户信息失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getUserList()
        // 提示修改成功
        this.$msg.success('更新用户信息成功！')
      })
    },
    async doDel(id) {
      //弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        '请问是否要永久删除该用户',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != 'confirm') {
        return this.$msg.info('已经取消删除')
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$axios.delete('users/' + id)
      //判断如果删除失败，就做提示
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      //修改成功的提示
      this.$msg.success(res.meta.msg)
      if (this.userList.length === 1) {
        this.queryData.pagenum--
      }
      //重新请求最新的数据
      this.getUserList()
    },
    async showRoleDialog(userInfo) {
      this.curUser = userInfo
      const { data: res } = await this.$axios({
        url: 'roles',
      })
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      console.log(res.data);
      this.selRoleList = res.data
      this.isRoleShow = true
    },
    async doSetRole() {
      const { data: res } = await this.$axios({
        url: `users/${this.curUser.id + 0}/role`,
        method: 'put',
        data: { rid: this.selRoleId },
      })
      console.log(res.data)
      if (res.meta.status !== 200) return this.$msg.error(res.meta.msg)
      this.isRoleShow = false
      this.getUserList()
    },
    setRoleDialogClose() {
      //当关闭对话框的时候，重置下拉框中的内容
      this.selRoleId = ''
      this.userData = {}
    },
  },
  created() {
    this.getUserList()
  },
}
</script>
<style  scoped>
html,
body,
#app {
  height: 100%;
  padding: 0;
  margin: 0;
}

.el-breadcrumb {
  margin-bottom: 15px;
}

.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
}

.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>

